import 'package:enjoy_plus/main.dart';
import 'package:enjoy_plus/utils/TokenUtil.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../model/counter_store.dart';
import '../../utils/ToastUtil.dart';
import '../../utils/eventbus.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});

  int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  Map userInfo = {'avatar': '', 'nickname': '', 'id': ''};

  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  @override
  void initState() {
    super.initState();
    eventBus.on<RefreshMine>().listen((event) {
      getProfile();
    });
    eventBus.on<RefreshProfile>().listen((event) {
      getProfile();
    });
  }

  // 当widget重新构建的时候调用该方法
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      getProfile();
    }
  }

  // 获取个人信息
  getProfile() async {
    var res = await Http.getInstance().get('/userInfo');
    debugPrint(res.toString());
    if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
    setState(() {
      userInfo = res['data'];
      debugPrint(userInfo.toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    final counterModel = Provider.of<CounterState>(context);
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: Text('我的${counterModel.counter}',
            style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
              padding: const EdgeInsets.all(10),
              child: GestureDetector(
                  onTap: () {
                    // Navigator.pushNamed(context, '/profile',
                    //     arguments: userInfo);
                    // context.goNamed('/profile', extra: userInfo);
                    context.push(
                      '/profile',
                      extra: userInfo,
                    );
                  },
                  child: Row(children: [
                    Row(children: [
                      ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: userInfo['avatar'] != '' &&
                                  userInfo['avatar'] != null
                              ? Image.network(userInfo['avatar'],
                                  width: 50, height: 50)
                              : Image.asset('assets/images/avatar_1.jpg',
                                  width: 50, height: 50)),
                      const SizedBox(width: 10),
                      Text(userInfo['nickName'] ?? '暂无昵称',
                          style: const TextStyle(
                              fontSize: 16, color: Colors.white))
                    ]),
                    const Spacer(),
                    const Row(children: [
                      Text(
                        '去完善信息',
                        style: TextStyle(color: Colors.white),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.white,
                        size: 13,
                      )
                    ])
                  ]))),
          Container(
              padding: const EdgeInsets.all(15),
              margin: const EdgeInsets.only(
                  top: 20, left: 10, right: 10, bottom: 20),
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(10)),
              child: Column(
                  children: menuList.map((item) {
                return SizedBox(
                    height: 50,
                    child: GestureDetector(
                      onTap: () {
                        if (item['title'] == '我的房屋') {
                          // Navigator.pushNamed(context, '/house_list');
                          context.push('/house_list');
                        }
                      },
                      child: Row(children: [
                        Row(
                          children: [
                            Image.asset(
                              item['icon'],
                              width: 20,
                              height: 20,
                            ),
                            const SizedBox(
                              width: 10,
                            ),
                            Text(
                              item['title'],
                              style: const TextStyle(fontSize: 16),
                            )
                          ],
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.arrow_forward_ios,
                          size: 12,
                          color: Colors.grey,
                        )
                      ]),
                    ));
              }).toList())),
          SizedBox(height: 30),
          ElevatedButton(
            onPressed: () {
              TokenManager().removeToken();
            },
            child: Text('退出登录'),
          ),
        ],
      ),
    );
  }
}
